package com.llianejapan.ToRoma;

import java.net.URLEncoder;
import java.util.Vector;

import com.llianejapan.KanjiLists.*;
import com.llianejapan.LlianeGlobal;
import com.llianejapan.R;
import com.llianejapan.Types.KanjiTypeOCR;
import com.llianejapan.Types.MatchScore2;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.text.ClipboardManager;
import android.view.View;
import android.widget.ArrayAdapter;

public class KanjiToRoma extends ListActivity{
	private Handler pb_handler = new Handler();
	private ProgressDialog pb_dialog;
	public KanjiToRoma zisse;
	public Bitmap kanji_bmp;
	public Canvas kanji_cvs;
	public Paint kanji_paint;
	public int pixelsA[];
	public int pixelsB[];
	public double score = 0;
	public int scorer = 0;

	@Override	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTheme(android.R.style.Theme_Black_NoTitleBar);
		zisse = this;
		pb_dialog = new ProgressDialog(this);
		pb_dialog.setTitle(getString(R.string.progress_title));
		pb_dialog.setMessage(getString(R.string.progress_FFT));
		pb_dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		pb_dialog.show();
		new Thread (new Runnable() {
			public void run() {
				match();
			}
		}).start();
	}    
	@Override
	protected void onListItemClick(android.widget.ListView l, View v, int position, long id)
	{	
		//Validation du choix
		Bitmap kanji_bmp = Bitmap.createBitmap(320, 200, Bitmap.Config.ARGB_8888);
		Canvas kanji_cvs = new Canvas(kanji_bmp);        	
		Paint kanji_paint = new Paint();        

		kanji_cvs.drawColor(Color.WHITE);
		kanji_paint.setStyle(Paint.Style.FILL);
		kanji_paint.setAntiAlias(true);
		kanji_paint.setColor(Color.BLACK);
		kanji_paint.setTextSize(180);
		kanji_paint.setTextAlign(Paint.Align.CENTER);
		/* TODO */
		kanji_cvs.drawText(kanjis2.elementAt((int)id), 160, 160, kanji_paint);
		ClipboardManager cb = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
		cb.setText(kanjis2.elementAt((int)id));
		LlianeGlobal.kanji2roma_bmpKanji = kanji_bmp;
		LlianeGlobal.kanji2roma_showRoma3.setText(mStrings.getItem((int) id));
		LlianeGlobal.wvurl = 
			"http://ks363797.kimsufi.com/anime/k/"+
		URLEncoder.encode(kanjis2.elementAt((int) id))
		+".htm";
		LlianeGlobal.kanji2roma_showRoma3.setTextSize(15);
		LlianeGlobal.kanji2roma_drawKanji.setImageBitmap(LlianeGlobal.kanji2roma_bmpKanji);		 
		finish();		
	}
	public void match_list(final KanjiTypeOCR[] klist, double[][] fftk)
	{
		for (i = 0; i < klist.length; i++)
		{		
			if (LlianeGlobal.option_strokes.isChecked()
					&& (LlianeGlobal.kanji2roma_strokes != 0)
					&& (LlianeGlobal.kanji2roma_strokes != klist[i].strokes_))
				continue;
			score = 0;
			curkanji = klist[i].kanji_;
			for (int fftn = 0; fftn < 10; fftn++)
			{
				double x_re = klist[i].fftv_[fftn].re();
				double x_im = klist[i].fftv_[fftn].im();
				double y_re = fftk[fftn][0];
				double y_im = fftk[fftn][1];
				double re_ = x_re - y_re;
				double im_ = x_im - y_im;
				score += im_ * im_ + re_ * re_;
			}
			kanjis.add(new MatchScore2(klist[i].kanji_, score));
		}		
	}
	public void match() {
		//Structure initialisation
		mStrings = new ArrayAdapter<String>(zisse, R.layout.kanjitoroma);		
		strings_v = new Vector<String>();
		kanjis2 = new Vector<String>();
		kanjis = new Vector<MatchScore2>();
		//Stretching the character
		int minx = 320;
		int miny = 200;
		int maxx = 0;
		int maxy = 0;
		for (int x = 0; x < 320; x++)
			for (int y = 0; y < 200; y++)
				if (LlianeGlobal.kanji2roma_bmpKanji.getPixel(x, y) == Color.BLACK)
				{
					if (x < minx)
						minx = x;
					if (x > maxx)
						maxx = x;
					if (y < miny)
						miny = y;
					if (y > maxy)
						maxy = y;
				}
		minx -= 5;
		miny -= 5;
		maxx += 5;
		maxy +=5;
		if (minx < 0)
			minx = 0;
		if (miny < 0)
			miny = 0;
		if (maxx > 320)
			maxx = 320;
		if (maxy > 200)
			maxy = 200;
		if (minx > maxx)
		{
			minx = 0; maxx = 50;
			miny = 0; maxy = 50;
		}
		Bitmap redim_bmp = Bitmap.createBitmap(LlianeGlobal.kanji2roma_bmpKanji,
				minx, miny, maxx - minx, maxy - miny);
		Bitmap scaled_bmp = Bitmap.createScaledBitmap(redim_bmp,
				128, 128, false);
		double score = 0;
		int scorer = 0;
		//Getting the picture pixels
		int pixelsA[] = new int[16384];
		Complex1D pixelsA_C = new Complex1D();
		pixelsA_C.x = new double[16384];
		pixelsA_C.y = new double[16384];
		scaled_bmp.getPixels(pixelsA, 0, 128, 0, 0, 128, 128);
		//Setting all pixels to Color.BLACK || Color.WHITE
		for (int x = 0; x < 16384; x++)
		{
			if (pixelsA[x] != Color.BLACK)	
			{
				pixelsA_C.x[x] = 1;
				pixelsA_C.y[x] = 0;
				pixelsA[x] = Color.WHITE;
			}
			else
			{
				pixelsA_C.x[x] = 0;
				pixelsA_C.y[x] = 0;
			}
		}
		//Computation of FFT
		ComplexDoubleFFT fftpa = new ComplexDoubleFFT(128*128);
		fftpa.ft(pixelsA_C);;
		double[][] fftk = new double[10][2];
		for (int fftn = 0; fftn < 10; fftn++)
		{
			fftk[fftn][0] = pixelsA_C.x[fftn] * 10000;
			fftk[fftn][0] = Math.floor(fftk[fftn][0] + 0.5);
			fftk[fftn][0] = fftk[fftn][0] / 10000;
			fftk[fftn][1] = pixelsA_C.y[fftn] * 10000;
			fftk[fftn][1] = Math.floor(fftk[fftn][1] + 0.5);
			fftk[fftn][1] = fftk[fftn][1] / 10000;
		}
		pb_handler.post(new Runnable() {
			public void run() {
				pb_dialog.setMessage(getString(R.string.progress_comparison));
				pb_dialog.show();
			}
		});
		//Debut des appels différenciés
		for (kn = 0; kn < KANJIML.kmlo.length; kn++)
		{	
			len = KANJIML.kmlo[kn].length;
			match_list(KANJIML.kmlo[kn], fftk);
		}

		//Classement
		pb_handler.post(new Runnable() {
			public void run() {
				pb_dialog.setMessage(getString(R.string.progress_sort));
				pb_dialog.show();
			}
		});
		int k = 0;
		double scoremin = -1;
		while (k < 75)
		{			
			score = -1;
			scorer = -1;
			for (int j = 0; j < kanjis.size(); j++)
			{
				if ((kanjis.elementAt(j).score_ >= 0) && 
						((kanjis.elementAt(j).score_ <= score) || (score == -1)))
				{
					score = kanjis.elementAt(j).score_;
					scorer = j;
				}
			}
			if (scorer == -1)
				break;
			if (scoremin == -1)
				scoremin = kanjis.elementAt(scorer).score_;
			kanjis2.add(kanjis.elementAt(scorer).kanji_);
			if (scoremin > 1)
				  strings_v.add(kanjis.elementAt(scorer).kanji_ + " " 
						+ ((int) ((scoremin / kanjis.elementAt(scorer).score_) * 100)) + " %");
				else if (score < 1)
					strings_v.add(kanjis.elementAt(scorer).kanji_ + " " 
							+ "100 %");
				else
					strings_v.add(kanjis.elementAt(scorer).kanji_ + " " 
							+ "< 1 %");
			kanjis.get(scorer).score_ = -2;
			k++;
		}

		//Ajout
		for (i = 0; i < strings_v.size(); i++)
			mStrings.add(strings_v.elementAt(i));
		pb_handler.post(new Runnable() {
			public void run() {
				pb_dialog.setMessage(getString(R.string.progress_done));						
				pb_dialog.show();
				setListAdapter(mStrings);
				pb_dialog.dismiss();
			}
		});

	};
	public int i;
	public String curkanji;
	public int kn;
	public int len;
	public Vector<MatchScore2> kanjis;
	public Vector<String> kanjis2;
	public Vector<String> strings_v;
	public ArrayAdapter<String> mStrings;
}